package com.trigsoft.applist;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class ContextDialog implements OnItemClickListener
{
	private Activity mCtx;
	private AdapterView<?> mAdapterView;
	private int mPosition;
	private AlertDialog dialog;
	private boolean inRecent;
	private boolean inList;
	private String pkg;
	private Cursor cursor;
	private String name;
	private String label;
	String cat;
	private PackageManager pm;
	private App app;
	private ResolveInfo ri;

	public ContextDialog(Activity context, AdapterView<?> adapterView, int position)
	{
		mCtx = context;
		mAdapterView = adapterView;
		mPosition = position;

		pm = mCtx.getPackageManager();
		final String[] firstItems = mCtx.getResources().getStringArray(R.array.context);
		final String REMOVE_FROM_RECENT = mCtx.getString(R.string.removeFromRecent);
		final String ADD_TO_RECENT = mCtx.getString(R.string.addToRecent);
		final String REMOVE_FROM_LIST = mCtx.getString(R.string.removeFromApp);
		final String ADD_TO_LIST = mCtx.getString(R.string.addToApp);
		List<String> contextMenu = new ArrayList<String>(java.util.Arrays.asList(firstItems));

		if (mAdapterView.getAdapter().getClass() == TaskAdapter.class)
		{
			inRecent = true;
			contextMenu.add(REMOVE_FROM_RECENT);
			Object obj = mAdapterView.getItemAtPosition(mPosition);
			if (obj.getClass() == ActivityManager.RecentTaskInfo.class)
			{
				ActivityManager.RecentTaskInfo task = (ActivityManager.RecentTaskInfo) obj;
				ri = pm.resolveActivity(task.baseIntent, 0);
				label = ri.loadLabel(pm).toString();
				pkg = ri.activityInfo.packageName;
				name = task.baseIntent.getComponent().getClassName();
				cat = DBHelper.getCurrentCat(pkg);
			} else
			{
				app = (App) obj;
				pkg = app.getPkgName();
				name = app.getName();
				label = app.getLabel();
				cat = app.getCat();
			}
			inList = DBHelper.queryInListByPKG(pkg);
			if (inList)
				contextMenu.add(REMOVE_FROM_LIST);
			else
				contextMenu.add(ADD_TO_LIST);
		} else if (context.getClass() == AppListAct.class)
		{
			inList = true;

			cursor = (Cursor) mAdapterView.getItemAtPosition(mPosition);
			pkg = cursor.getString(cursor.getColumnIndex(DBHelper.KEY_PKG));
			label = cursor.getString(cursor.getColumnIndex(DBHelper.KEY_LABEL));
			name = cursor.getString(cursor.getColumnIndex(DBHelper.KEY_NAME));
			cat = cursor.getString(cursor.getColumnIndex(DBHelper.KEY_CAT));

			int inRecent = cursor.getInt(cursor.getColumnIndex(DBHelper.KEY_INRECENT));
			if (inRecent == 1)
			{
				this.inRecent = true;
				contextMenu.add(REMOVE_FROM_RECENT);
			} else
			{
				this.inRecent = false;
				contextMenu.add(ADD_TO_RECENT);
			}
			contextMenu.add(REMOVE_FROM_LIST);
		} else if (context.getClass() == StatisticsAct.class)
		{
			cursor = (Cursor) mAdapterView.getItemAtPosition(mPosition);
			pkg = cursor.getString(cursor.getColumnIndex(DBHelper.KEY_PKG));
			label = cursor.getString(cursor.getColumnIndex(DBHelper.KEY_LABEL));
			name = cursor.getString(cursor.getColumnIndex(DBHelper.KEY_NAME));
			cat = cursor.getString(cursor.getColumnIndex(DBHelper.KEY_CAT));
		}
		ListView contexts = new ListView(mCtx);
		contexts.setAdapter(new ArrayAdapter<String>(mCtx, R.layout.context_item, contextMenu));
		contexts.setOnItemClickListener(this);

		dialog = new AlertDialog.Builder(mCtx).setView(contexts).create();
	}

	private void createShortcut()
	{
		Bitmap bitmap;

		if (mAdapterView.getAdapter().getClass() == TaskAdapter.class)
		{
			Object obj = mAdapterView.getItemAtPosition(mPosition);
			if (obj.getClass() == ActivityManager.RecentTaskInfo.class)
			{
				bitmap = ((BitmapDrawable) ri.loadIcon(pm)).getBitmap();
			} else
			{
				bitmap = IconCache.icons.get(app.getLabel());
			}
		} else
		{
			//Cursor cursor = (Cursor) mAdapterView.getItemAtPosition(mPosition);

			//pkg = cursor.getString(cursor.getColumnIndex(DBHelper.KEY_PKG));
			if (name == null)
			{
				Toast.makeText(mCtx, "此程序没有应用界面,无法添加快捷方式，请查看是用说明。", Toast.LENGTH_SHORT).show();
				return;
			}
			bitmap = IconCache.icons.get(label);

		}
		final DisplayMetrics dm = new DisplayMetrics();
		mCtx.getWindowManager().getDefaultDisplay().getMetrics(dm);
		final int iconSize = (int) (mCtx.getResources().getDimension(android.R.dimen.app_icon_size) * dm.density);

		Intent shortcutIntent = new Intent(Intent.ACTION_MAIN);
		shortcutIntent.addCategory(Intent.CATEGORY_LAUNCHER);
		Intent intent = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
		shortcutIntent.setComponent(new ComponentName(pkg, name));
		shortcutIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);

		intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
		intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, label);
		Bitmap icon = Bitmap.createScaledBitmap(bitmap, iconSize, iconSize, true);
		intent.putExtra(Intent.EXTRA_SHORTCUT_ICON, icon);
		mCtx.sendBroadcast(intent);

	}

	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
	{
		/* User clicked so do some stuff */
		switch (arg2)
		{
		case 0:
			createShortcut();
			break;
		case 1:
			uninstall();
			break;
		case 2:
			share();
			break;
		case 3:
			cat();
			break;
		case 4:
			updateInRecent();
			break;
		case 5:
			updateInList();
			break;
		}
		dialog.dismiss();
	}

	private void share()
	{
		// TODO Auto-generated method stub
		Intent it = new Intent(Intent.ACTION_SEND);
		it.setType("text/plain");

		it.putExtra(Intent.EXTRA_TEXT, label + "(" + pkg + ") --- 由AppList分享");
		mCtx.startActivity(it);
	}

	public void show()
	{
		dialog.show();
	}

	private void uninstall()
	{
		// TODO Auto-generated method stub
		Uri packageURI = Uri.parse("package:" + pkg);
		Intent uninstallIntent = new Intent(Intent.ACTION_DELETE, packageURI);
		mCtx.startActivity(uninstallIntent);
	}

	private void updateInList()
	{
		if (inList)
			DBHelper.updateInList(DBHelper.notIn, name);
		else
			DBHelper.updateInList(DBHelper.in, name);
		((AppListAct) mCtx).load();
	}

	private void updateInRecent()
	{
		NotInRecent nir = new NotInRecent(mCtx);
		if (inRecent)
		{
			String n = DBHelper.updateInRecent(DBHelper.notIn, pkg, name);
			nir.addFromContext(pkg, n);
		} else
		{
			String n = DBHelper.updateInRecent(DBHelper.in, pkg, name);
			nir.remove(pkg, n);
		}
		nir.save(mCtx);
		((AppListAct) mCtx).load();
	}

	private void cat()
	{
		new CatDialog(mCtx, label, pkg, cat).show();
	}

}
